/**
 * @developer：MR·Feng
 * 封装请求
 */

import qs from "querystring";
import { message } from "antd";

// 跳转
const jumppage = (value) => {
    if (value === 302) {
        message.error(`访问失败：${value}`);
        setTimeout(() => {
            window.location.href = '/login';
        }, 2500);
    };
}

// GET
export async function httpGet(url, params, headers) {
    const header = {
        ...{
            credentials: "include",
            Accept: "application/json,text/plain,*/*" /* 格式限制：json、文本、其他格式 */ ,
            "Content-Type": "application/json;charset=UTF-8" /* 请求内容类型 */ ,
            Cookie: "SESSION=M2VlNmM3YTItZDExMC00OWQ5LWI3OTctM2I1NzQwZDA1YmMy",
        },
        ...(headers || {}),
    };
    const result = await fetch(url, {
        method: "GET",
        headers: header,
        body: qs.stringify(params),
    }).then((resolve) => {
        jumppage(resolve.status);
        resolve.json();
    });
    if(result) jumppage(result.code);
    return result;
}

// POST
export async function httpPost(url, params, headers) {
    const header = {
        ...{
            credentials: "include",
            Accept: "application/json,text/plain,*/*" /* 格式限制：json、文本、其他格式 */ ,
            "Content-Type": "application/json;charset=UTF-8" /* 请求内容类型 */ ,
            Cookie: "SESSION=M2VlNmM3YTItZDExMC00OWQ5LWI3OTctM2I1NzQwZDA1YmMy",
        },
        ...(headers || {}),
    };
    const result = await fetch(url, {
        method: "POST",
        headers: header,
        credentials: "include",
        body: JSON.stringify(params),
    }).then((resolve) => {
        jumppage(resolve.status);
        return resolve.json();
    })
    if(result) jumppage(result.code);
    return result;
}